/*
 * ISSOConstants.java
 * 
 * Version information
 * 
 * Feb 20, 2006
 * 
 * Copyright (c) AmSoft Systems, 2006
 */
package net.amsoft.iservice.isso.util;

import java.util.Hashtable;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;

/**
 */
public class ISSOConstants {
    private static final Logger oLog = Logger.getLogger(ISSOConstants.class);
    public static ResourceBundle ISSOBUNDLE = ResourceBundle
            .getBundle("issoResources");
    public static final short STATE_PENDING = 0;
    public static final short STATE_ACTIVE = 1;
    public static final short STATE_BANNED = 2;
    public static final short STATE_INACTIVE = 3;
    private static Hashtable<Integer, String> ohErrors = null;
    private static Hashtable<String, String> oChallangeQuestion = null;
    // private static Hashtable oIBrokerTable = null;
    public static final int FIELD_NAME = 0;
    public static final int GETTER = 1;
    public static final int RETURN_TYPE = 2;
    public static final int SETTER = 3;
    public static final int DB_FIELD = 4;
    public static final short SESSION = 0;
    public static final short MACHINE = 1;
    public static final short RESPONSE = 2;
    // session objects names
    public static final String SESSION_LOGIN_OBJ = "LoginData";
    public static final String SESSION_IBROKER_OBJ = "IBrokerData";
    public static final String SESSION_CHALLENGE_QUESTIONS = "ChallengeQuestions";
    public static final String SESSION_SHOW_GREETING = "ShowGreeting";
    public static final String REQ_ATTRIB_GREETING = "Greeting";
    public static final String REQ_ATTRIB_CONFIG = "ConfigForm";
    public static final String REQ_ATTRIB_IS_PASSIVE = "IsPassive";
    public static final String REQ_ATTRIB_PROVIDER_NAME = "ProviderName";
    public static final String REQ_ATTRIB_LOGOUT_FRM = "LogoutForm";
    public static final String REQ_ATTRIB_SYNONYM = "loggedInSynonym";
    public static final String SESSION_LOGIN_HASH_OBJ = "SpLoginHashInfo";
    

    // request parameters names
    public static final String REQ_PARAM_STEP = "step";
    public static final String REQ_PARAM_STEP_VALUES = "save";
    public static final String REQ_PARAM_ACTION = "action";
    public static final String REQ_PARAM_ACTION_LOGOUT = "logout";
    public static final String REQ_PARAM_ACTION_CANCEL = "cancel";
    public static final String REQ_PARAM_INAME = "iname";
    public static final String REQ_PARAM_EMAIL = "email";
    public static final String REQ_PARAM_GINU = "globalINumber";
    public static final String REQ_PARAM_CHALLENGE_QUEST = "challengeQuest";
    public static final String REQ_PARAM_RECOVERY_ANS = "recoveryAnswer";
    public static final String REQ_PARAM_SPXRI = "spXri";
    
    // action forwards
    public static final String CHKLOGIN_FWD = "CheckLogin";
    public static final String LOGOUT_FRD = "Logout";
    public static final String INAME_FWD = "iname";
    public static final String SUCCESS_FWD = "success";
    public static final String MESSAGE_FWD = "message";
    public static final String FAILURE_FWD = "failure";
    public static final String CHALLENGE_FWD = "challenge";
    public static final String WELCOME_FWD = "welcome";
    public static final String SHOW_CONFIG_FWD = "showConfig";
    public static final String RETRY_FWD = "retry";

    // error keys
    public static final String ERR_INVALID_REQUEST = "invalid.request";
    public static final String ERR_INAME_NOT_FOUND = "iname.not.resolved";
    public static final String ERR_WRONG_PWD = "incorrect.password";
    public static final String ERR_WRONG_EXISTING_PWD = "invalid.existing.password";
    public static final String ERR_PWD_NOT_SAME = "password.not.same";
    public static final String ERR_INVALID_PWD = "invalid.password";
    public static final String ERR_INVALID = "invalid";
    public static final String ERR_EMAIL_MISMATCH = "email.iname.mismatch";
    public static final String ERR_INVALID_REQ_MADE = "invalid.request.made";
    public static final String ERR_INAME_MISMATCH = "act.token.iname.mismatch";
    public static final String ERR_SESSION_MISMATCH = "session.iname.mismatch";
    public static final String ERR_INCORRECT_ANSWER= "incorrect.answer";
    public static final String ERR_EXCEEDED_ATTEMPTS = "exeeded.attempts";
    public static final String ERR_INVALID_EMAIL = "err.invalid.email";
    public static final String ERR_PASSWD_LENGTH = "err.passwd.length";
    public static final String ERR_CHALLENEGE_ANSWER= "err.challengeAnswer";
    
    // message keys
    public static final String MSG_CONFIG_CANCELED = "config.canceled";
    public static final String MSG_CONFIG_SAVED = "config.saved";
    public static final String MSG_LOGIN_SUCCESS = "login.success";
    public static final String MSG_LOGOUT_SUCCESS = "logout.success";
    public static final String MSG_PASSWORD_UPDATED = "password.update";
    public static final String MSG_ACCOUNT_ALREADY_ACTIVE = "account.already.active";
    public static final String MSG_ACCOUNT_NOT_ACTIVE = "account.not.active";
    public static final String MSG_NOT_ABLE_TO_PERFORM_OPERATION = "unable.to.perform.operation";
    
    //configuration field constants
    public static final String FIRST_NAME = "label.firstName";
    public static final String LAST_NAME = "label.lastName";
    public static final String GREETING = "label.personalizedGreeting";
    public static final String EMAIL_ADDRESS = "label.email";
    public static final String CHALLENEGE_ANSWER= "label.challengeAnswer";
    
    // email constants
    public static final String EMAIL_SUBJECT = "email.forgot.pwd.subject";
    public static final String EMAIL_BODY = "email.forgot.pwd.request";
    
    public static final String EMAIL_CHNG_PWD_SUB = "email.change.pwd.subject";
    public static final String EMAIL_CHNG_PWD_BODY = "email.forgot.pwd.notification";
    
    public static final String SENDER_NAME = "sender.name";
    // Cookie Age
    public static final int VALIDITY_SESSION_CLIENT = Integer
            .parseInt(getProperty(ISSOBUNDLE, "session.client.validity.year"))
            * 365 * 24 * 60 * 60;
    public static final int VALIDITY_SESSION_SERVER = Integer
            .parseInt(getProperty(ISSOBUNDLE, "session.server.validity.hours")) * 60 * 60;
    public static final int VALIDITY_MACHINE_CLIENT = Integer
            .parseInt(getProperty(ISSOBUNDLE, "machine.client.validity.year"))
            * 365 * 24 * 60 * 60;
    public static final int VALIDITY_MACHINE_SERVER = Integer
            .parseInt(getProperty(ISSOBUNDLE, "machine.server.validity.days")) * 24 * 60 * 60;
    public static final String MACHINE_COOKIE_NAME = getProperty(ISSOBUNDLE,
            "machine.cookie.name");
    public static final String SESSION_COOKIE_NAME = getProperty(ISSOBUNDLE,
            "session.cookie.name");
    
    //Name and validity of Cookie for Same page login
     public static final int VALIDITY_SERVICE_COOKIE = Integer
           .parseInt(getProperty(ISSOBUNDLE, "service.validity.hours")) * 60 * 60;
     public static final String SERV_ID_COOKIE_NAME = getProperty(ISSOBUNDLE,
           "serv.id.cookie.name");
    
    public static final String XRI_SCHEME = "xri://";
    public static final int PRIORITY_HIGHEST = 0;
    // public static final byte[] ARTIFACT_TYPE = {0x0000, 0x0004};

    // Authentication Context Classes
    private static Hashtable<String, Integer> racPriorityMap = null;
    private static final String RAC_IP = "urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocol";
    private static final String RAC_IP_PASSWORD = "urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocolPassword";
    private static final String RAC_KERBEROS = "urn:oasis:names:tc:SAML:2.0:ac:classes:Kerberos";
    private static final String RAC_MOBILE_ONE_FACTOR_UNREG = "urn:oasis:names:tc:SAML:2.0:ac:classes:MobileOneFactorUnregistered";
    private static final String RAC_MOBILE_TWO_FACTOR_UNREG = "urn:oasis:names:tc:SAML:2.0:ac:classes:MobileTwoFactorUnregistered";
    private static final String RAC_MOBILE_ONE_FACTOR_CONTRACT = "urn:oasis:names:tc:SAML:2.0:ac:classes:MobileOneFactorContract";
    private static final String RAC_MOBILE_TWO_FACTOR_CONTRACT = "urn:oasis:names:tc:SAML:2.0:ac:classes:MobileTwoFactorContract";
    private static final String RAC_PASSWORD = "urn:oasis:names:tc:SAML:2.0:ac:classes:Password";
    public static final String RAC_PASSWORD_PROTECTED_TRANSPORT = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport";
    public static final String RAC_PREVIOUS_SESSION = "urn:oasis:names:tc:SAML:2.0:ac:classes:PreviousSession";
    private static final String RAC_PK_X509 = "urn:oasis:names:tc:SAML:2.0:ac:classes:X509";
    private static final String RAC_PK_PGP = "urn:oasis:names:tc:SAML:2.0:ac:classes:PGP";
    private static final String RAC_PK_SPKI = "urn:oasis:names:tc:SAML:2.0:ac:classes:SPKI";
    private static final String RAC_PK_XML = "urn:oasis:names:tc:SAML:2.0:ac:classes:XMLDSig";
    private static final String RAC_SMARTCARD = "urn:oasis:names:tc:SAML:2.0:ac:classes:Smartcard";
    private static final String RAC_SMARTCARD_PKI = "urn:oasis:names:tc:SAML:2.0:ac:classes:SmartcardPKI";
    private static final String RAC_SOFTWARE_PKI = "urn:oasis:names:tc:SAML:2.0:ac:classes:SoftwarePKI";
    private static final String RAC_TELEPHONY = "urn:oasis:names:tc:SAML:2.0:ac:classes:Telephony";
    private static final String RAC_TELEPHONY_NOM = "urn:oasis:names:tc:SAML:2.0:ac:classes:NomadTelephony";
    private static final String RAC_TELEPHONY_PER = "urn:oasis:names:tc:SAML:2.0:ac:classes:PersonalTelephony";
    private static final String RAC_TELEPHONY_AUTH = "urn:oasis:names:tc:SAML:2.0:ac:classes:AuthenticatedTelephony";
    private static final String RAC_SECURE_REMOTE_PASSWORD = "urn:oasis:names:tc:SAML:2.0:ac:classes:SecureRemotePassword";
    private static final String RAC_SSL_TLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:TLSClient";
    private static final String RAC_TIMESYNC_TOKEN = "urn:oasis:names:tc:SAML:2.0:ac:classes:TimeSyncToken";
    private static final String RAC_UNSPECIFIED = "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified";
    
    // Authentication Context Comparison types
    public static final String RAC_EXACT = "exact";
    public static final String RAC_MINIMUM = "minimum";
    public static final String RAC_MAXIMUM = "maximum";
    public static final String RAC_BETTER = "better";

    // Requested Authentication Contexts and Comparison type
    public static final String RAC_NAMES_LIST = ISSOBUNDLE.getString("rac.names.list");
    public static final String RAC_COMPARISON_TYPE = ISSOBUNDLE.getString("rac.comparison.type");
    
    public static final void init() {
        if (ohErrors == null) {
            ohErrors = new Hashtable<Integer, String>();
            // user exception
            ohErrors.put(1001, "Existing Password is incorrect");
            ohErrors.put(1000, "Email address is not valid");
///            ohErrors.put(1005, " User could not be logged in");
///            ohErrors.put(new Integer(1002), "Synonym does not exist");
//            // system exceptions
///            ohErrors.put(2000, "GlobalINumber already exists ");
///            ohErrors.put(2001, "Synonym already exists");
///            ohErrors.put(2003, "SEP is not in corect format");
            ohErrors.put(2006, "GlobalInumber does not exist");
            ohErrors.put(2007, "Account is not active");
//            ohErrors.put(2008, "SessionIndex does not exist");
            ohErrors.put(2009, "Session is invalid");
            ohErrors.put(2010, "User does not belong to this IBroker");
            ohErrors.put(2011, "Hash Collision");
///            ohErrors.put(2012, "IBroker could not be  created");
///            ohErrors.put(2013, "Artifact does not exist");
            ohErrors.put(2004, "IBroker not provisioned");
///            ohErrors.put(2014, "Invalid Fields");
            ohErrors.put(2015, "Synonym does not exist");
            ohErrors.put(2016, "No permissions to insert the supplied Fields");
///            ohErrors.put(2017, "Data Could not be deleted");
///            ohErrors.put(2018,
//                    "Specified Operations was not performed successfully");
///            ohErrors.put(2019, "Invalid /BlankEmail Id ");
///            ohErrors.put(2020, "No Synonyms Found");
//            ohErrors
///                    .put(2021,
//                            "No permissions to update one or more of the specified fields");
///            ohErrors.put(2022, "Data could not be updated");
///            ohErrors.put(2023, "Synonyms could not be updated");
///            ohErrors.put(2024, "Principal could not created");
///            ohErrors.put(2025, "Session could not created");
///            ohErrors.put(2026, "Machine Cookies could not created");
///            ohErrors.put(2027, "Response could not created");
            ohErrors.put(2028, "InSufficient Data");
///            ohErrors.put(2029, "Invalid Session type specified");
///            ohErrors.put(2030, "No matching record found ");
///            ohErrors.put(2031, "IBroker already exist");
///            ohErrors.put(2032, "Machine Cookie Does Not exist");
            ohErrors.put(2033, "Session Does Not exist");
            ohErrors.put(2034, "Iname/Inumber can't be resolved");
            ohErrors.put(2035, "Session does not belong to Principal");
///            ohErrors.put(2036, "This Method is currently not implemented.");
            ohErrors.put(2037, "Account is already active");
            ohErrors.put(101, "Duplicate");
            ohErrors.put(102, "Parse Error");
        }
    }

    private static final void initializeQuestions() {
        if (oChallangeQuestion == null) {
            oChallangeQuestion = new Hashtable<String, String>();
            oChallangeQuestion.put("1", "What is your mother's maiden name?");
            oChallangeQuestion.put("2", "What is your pet's name?");
            oChallangeQuestion.put("3", "What is your city of birth?");
            oChallangeQuestion.put("4", "Which is your favourite sport?");
            oChallangeQuestion.put("5",
                    "Which is your favourite basketball team?");
            oChallangeQuestion.put("6",
                    "What is your favourite holiday destination?");
            oChallangeQuestion.put("7", "What city do you live in?");
            oChallangeQuestion.put("8", "What is your favourite car?");
            oChallangeQuestion.put("9", "What are your initials?");
        }
    }

    // public static final void initializeIbrokerData() {
    // if (oIBrokerTable == null || oIBrokerTable.size() == 0) {
    // oIBrokerTable = new Hashtable();
    // ResourceBundle oBundle = ResourceBundle.getBundle("ibrokers");
    // Enumeration oBundleKeys = oBundle.getKeys();
    // while (oBundleKeys.hasMoreElements()) {
    // String sIBname = (String) oBundleKeys.nextElement();
    // String sIBXris = oBundle.getString(sIBname);
    // oIBrokerTable.put(sIBname, sIBXris);
    // }
    // }
    // }

    public static final String getProviderID(String sIBrokerName) {
        if (sIBrokerName == null) {
            return null;
        }
        try {
            ResourceBundle oBrokerBundle = ResourceBundle.getBundle("ibrokers");
            String sXri = oBrokerBundle.getString(sIBrokerName);
            String[] fields = sXri.split(",");
            if (fields != null && fields.length > 0) {
                return fields[0].trim();
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    public static final String getSPXri(String sIBrokerName) {
        if (sIBrokerName == null) {
            return null;
        }
        try {
            ResourceBundle oBrokerBundle = ResourceBundle.getBundle("ibrokers");
            String sXri = oBrokerBundle.getString(sIBrokerName);
            String[] fields = sXri.split(",");
            if (fields != null && fields.length > 0) {
                return fields[1].trim();
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    public static final Hashtable getChallangeQuestions() {
        if (oChallangeQuestion == null)
            initializeQuestions();
        return oChallangeQuestion;
    }

    public static final String getError(int iErrorCode)
            throws NullPointerException {
        if (ohErrors == null) {
            init();
        }
        return (String) ohErrors.get(new Integer(iErrorCode));
    }

    private static final String getProperty(ResourceBundle oBundle, String key) {
        try {
            return oBundle.getString(key);
        } catch (Exception e) {
            oLog.fatal("getProperty(): key: [" + key + "] not found");
            return "";
        }
    }

    /**
     * Initializes authentication contexts map
     *
     */
    public static final void initializeRACPriorityMap() {
        if (racPriorityMap==null)
        {
            racPriorityMap = new Hashtable<String, Integer>();
            racPriorityMap.put(RAC_IP, 1);
            racPriorityMap.put(RAC_IP_PASSWORD, 2);
            racPriorityMap.put(RAC_KERBEROS, 3);
            racPriorityMap.put(RAC_MOBILE_ONE_FACTOR_UNREG, 4);
            racPriorityMap.put(RAC_MOBILE_TWO_FACTOR_UNREG, 5);
            racPriorityMap.put(RAC_MOBILE_ONE_FACTOR_CONTRACT, 6);
            racPriorityMap.put(RAC_MOBILE_TWO_FACTOR_CONTRACT, 7);
            racPriorityMap.put(RAC_PASSWORD, 8);
            racPriorityMap.put(RAC_PASSWORD_PROTECTED_TRANSPORT, 9);
            racPriorityMap.put(RAC_PREVIOUS_SESSION, 10);
            racPriorityMap.put(RAC_PK_X509, 11);
            racPriorityMap.put(RAC_PK_PGP, 12);
            racPriorityMap.put(RAC_PK_SPKI, 13);
            racPriorityMap.put(RAC_PK_XML, 14);
            racPriorityMap.put(RAC_SMARTCARD, 15);
            racPriorityMap.put(RAC_SMARTCARD_PKI, 16);
            racPriorityMap.put(RAC_SOFTWARE_PKI, 17);
            racPriorityMap.put(RAC_TELEPHONY, 18);
            racPriorityMap.put(RAC_TELEPHONY_NOM, 19);
            racPriorityMap.put(RAC_TELEPHONY_PER, 20);
            racPriorityMap.put(RAC_TELEPHONY_AUTH, 21);
            racPriorityMap.put(RAC_SECURE_REMOTE_PASSWORD, 22);
            racPriorityMap.put(RAC_SSL_TLS, 23);
            racPriorityMap.put(RAC_TIMESYNC_TOKEN, 24);
            racPriorityMap.put(RAC_UNSPECIFIED, 25);
        }
    }
    
    /**
     * Checks if authentication contexts map is initialized. If not, then 
     * initialize it. Returns the priority of the specified authentication 
     * context if it is there in the map else returns -1 <br>
     *  
     * @param racName
     * 		Authentication context whose priority has to be returned
     * 
     * @return int 
     */
    public static final int getPriority(String racName) {
        if (racPriorityMap == null) {
            initializeRACPriorityMap();
        }
        if (racPriorityMap.get(racName)==null)
            return -1;
        else
            return (int) racPriorityMap.get(racName);
    }
    
}
